package com.heima.user.service.impl;

import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import com.jcraft.jsch.jce.MD5;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

/**
 * @author shiminghui
 * @date 2024/10/28 20:08
 * @description: TODO
 */
@Service
@Transactional
@Slf4j
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {


    @Override
    public ResponseResult login(LoginDto dto) {
        //用户登录
        if (StringUtils.isNotEmpty(dto.getPhone()) && StringUtils.isNotEmpty(dto.getPassword())) {
            //根据电话号码查询用户
            ApUser user = getOne(new LambdaQueryWrapper<ApUser>().eq(ApUser::getPhone, dto.getPhone()));
            if (user == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在"); //返回用户不存在
            }
            //校验密码是否正确
            String password = dto.getPassword();
            String salt = user.getSalt();
            // 密码加密
            String md5Password = DigestUtils.md5DigestAsHex((password + salt).getBytes());
            if (!md5Password.equals(user.getPassword())) {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);//返回密码错误
            }
            //生成jwt
            String token = AppJwtUtil.getToken(user.getId().longValue());
            HashMap<String, Object> map = new HashMap<>();
            map.put("token", token);
            //返回用户信息
            user.setSalt(null);
            user.setPassword(null);
            map.put("user", user);
            return ResponseResult.okResult(map);
        }
        //游客登录
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", AppJwtUtil.getToken(0L));
        return ResponseResult.okResult(map);
    }
}
